import React from "react";
import ReactDOM from "react-dom";
import cover from "../../assets/image/登录.webp";
import cookie from "js-cookie";
import { Form, Input, Button, message } from "antd";
import Router from "../../router/index";
import UserCom from "../../components/UserCom";
import api from "../../api";
const Login = (props) => {
  const login = async (values) => {
    const res = await api.login({ username: values.username, password: values.password });
    if (typeof res.data !== "string") {
      const info = await api.getUserInfo({ id: res.data.userData.id });
      await cookie.set("token", res.data.token);
      await window.sessionStorage.setItem("userData", JSON.stringify(info.data));
      await ReactDOM.render(<Router />, document.getElementById("root"));
      props.history.push("/workbench");
      message.success("登录成功");
    } else {
      message.error(res.data);
    }
  };
  return (
    <UserCom cover={cover}>
      <div className="login-main">
        <div className="login-title">系统登录</div>
        <Form name="basic" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} initialValues={{ remember: true }} autoComplete="off" onFinish={login}>
          <Form.Item label="账户" name="username" rules={[{ required: true, message: "请输入用户名!" }]}>
            <Input />
          </Form.Item>
          <Form.Item label="密码" name="password" rules={[{ required: true, message: "请输入密码!" }]}>
            <Input.Password />
          </Form.Item>
          <div className="login-btn-box">
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </div>
        </Form>
        <div
          className="or-box"
          onClick={() => {
            props.history.push("/register");
          }}
        >
          Or 注册用户
        </div>
      </div>
    </UserCom>
  );
};

export default Login;
